package cn.jinjimi.app.search;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 查询器
 * <p/>
 * Created by jinsen on 15/12/7.
 */
public abstract class BaseProvider implements IProvider {
    /**
     * 查询被取消
     */
    public static final int QUERY_STATE_CANCEL = -1;

    /**
     * 查询完成
     */
    public static final int QUERY_STATE_OK = 0;

    /**
     * 查询失败
     */
    public static final int QUERY_STATE_FAIL = -2;


    //取消查询
    protected boolean mCancelQuery = false;

    /**
     * 每一页返回多少数据
     * 默认50条
     */
    private int mPagerCount = 50;


    private List<Record> mResultList;

    //结果监听器
    private SearchResultListener mResultListner;

    protected boolean mHasNextPager = false;

    /**
     * 取消查询
     * <p/>
     * 在分页查询时,如果满一页了则暂停查询
     */
    protected boolean STOP_QUERY = false;

    public BaseProvider(SearchResultListener listener) {
        this(listener, -1);
    }

    public BaseProvider(SearchResultListener listener, int pageCount) {
        this.mResultList = new ArrayList<Record>();
        this.mResultListner = listener;
        this.mPagerCount = pageCount;
    }


    public abstract int doQuery(String key, int startIndex);

    /**
     * 取消查询
     */
    public void cancelQuery() {
        mCancelQuery = true;
        mResultList.clear();
        mResultListner.onQueryCanceled();
    }

    /**
     * 查询 默认从开始位置查询
     *
     * @param key
     * @return
     */
    public final int query(String key) {
        return query(key, 0);
    }

    /**
     * 查询, 从指定的位置开始查询
     *
     * @param key
     * @param startIndex
     * @return
     */
    public final int query(String key, int startIndex) {
        mResultList.clear();
        STOP_QUERY = false;
        mCancelQuery = false;
        if (!isValidKey(key))
            return QUERY_STATE_FAIL;
        return doQuery(key, startIndex);
    }

    public final void addResult(Record record) {
        if (mResultList == null)
            return;
        if(record != null)
            mResultList.add(record);

        if (mResultList.size() == mPagerCount || !mHasNextPager) {
            STOP_QUERY = true;
            mResultListner.onQueryResultGened(mResultList, mHasNextPager);
        }
    }

    public void sendEmptyCallback(){
        mResultListner.onQueryResultGened(null,false);
    }

    //检查查询关键字是否合法
    private boolean isValidKey(String key) {
        return !(TextUtils.isEmpty(key) ||
                (key.trim().length() == 0));
    }
}
